#include "Utility.h"
#include "MappingDialog.h"
#include "DIVA_Application.h"

#include <QtGui/QMainWindow>
#include <QtCore/QEventLoop>

std::pair< WOP_Entry*, xMappingTree* > createMappingFromUI( WOP_Entry * entry ) {
	MappingDialog * dialog = DIVA_Application::getInstance()->getMappingDialog();
	dialog->setCurrentEntry( entry );
	dialog->show();

	/*
	NOTE dirty cast
	We should use dynamic_cast or qobject_cast here to avoid error
	But using DIVA_Application::parentWidget to retrive the main xDiva window is a dirty hack already
	*/
	QMainWindow * mainWindow = static_cast< QMainWindow * >( DIVA_Application::getInstance()->parentWidget() );
	// dump visiblity state for log window etc.
	auto state = mainWindow->saveState();
	mainWindow->hide();

	QEventLoop wait;
	wait.connect( dialog, SIGNAL( finished() ), SLOT( quit() ) );
	wait.exec();

	mainWindow->show();
	mainWindow->restoreState( state );

	if( !dialog->isFinished() ) {
		return std::make_pair< WOP_Entry *, xMappingTree * >( nullptr, nullptr );
	}

	if( dialog->getRootWOP() ) {
		entry = dialog->getRootWOP();
	}

	return std::make_pair( entry, dialog->getMappingTree() );
}
